import mqtt from 'mqtt'
import iconv from 'iconv-lite';

export default {
  initMqtt (ipcMain, mqttObject) {
    // if (mqtt.connected) {

    //   // 重复连接mqtt
    //   ipcMain.reply('start-mqtt-connect-reply', '重复连接mqtt')
    //   return
    // }

    // 连接选项
    const options = {
      keepalive: 20,
      connectTimeout: 10000, // 超时时间
      // 认证信息
      clientId: mqttObject.sessionId || 'NGSA000001',
      username: '',
      password: '',
    }
    let mqttServerAddress = mqttObject.serviceInstanceIpAddress || '192.168.63.182'
    const mqttUrl = 'mqtt://' + mqttServerAddress + ':1222/mqtt'
    // const client = mqtt.connect('ws://localhost:9003', options)
    // const client = mqtt.connect('mqtt://127.0.0.1:1883/mqtt', options)
    const client = mqtt.connect(mqttUrl, options)

    client.on('reconnect', (error) => {
      console.log('正在重连:', error)
    })

    client.on('error', (error) => {
      console.log('连接失败:', error)
    })

    client.on('connect', (e) => {

      console.log('成功连接服务器')
      var ret = {
        success: true,
        msg: 'connect mqtt server success',
        code: 200
      }
      ipcMain.reply('start-mqtt-connect-reply', ret)

      // 一次订阅多个主题  获取设备类型的 业务处理
      client.subscribe('device/' + mqttObject.deviceSerialNo, {
        qos: 2
      }, (error) => {
        if (!error) {
          console.log('订阅成功')
          //会覆盖上一条记录 用别的主题
          ipcMain.reply('mqtt-subscribe-connect-reply', 'subscribe topic success')

          /* client.publish('api/AutoCreate', '设备订阅测试', {
            qos: 2,
            rein: false
          }, (error) => {
            console.log(error || '发布成功')
          }) */
        }
      })
    })

    // 监听接收消息事件
    client.on('message', (topic, message) => {
      console.log('收到来自', topic, '的消息', message.toString())
      // var mqttMessage = iconv.decode(message, 'gbk')
      var mqttMessage = iconv.decode(message, 'utf-8')
      console.log('收到来自', topic, '的消息', mqttMessage)
      ipcMain.reply('mqtt-server-message-topic', mqttMessage)
    })

    /*     // 发布消息
        if (!client.connected) {
          console.log('客户端未连接')
          return
        } */
    return client
  },
  sendMqttMessage (ipcMain, client, url, message) {
    // 发布消息
    if (!client || !client.connected) {
      console.log('客户端未连接')
      client.end()
      ipcMain.reply('send-mqtt-client-message-reply', '客户端未连接')
      return false
    }
    if (!message || message === '') {
      message = {
        dt: {
          idInfo: {
            idNu: '360103197610122231',
            name: 'abc'
          },
          nGenFullTractorNo: 'a|b|toms|suf',
          tcCode: '208609',
          ip: '192.168.63.182',
          idCard: '360103197610122231',
        },
        ic: 'AutoCreate',
        sn: 'NGSA000001',
        id: 1234567,
        en: false
      }
    }

    message = JSON.stringify(message)

    client.publish(url, message, {
      qos: 2
    }, (error) => {
      // let emptyMsg = 'sendMqttMessage 异常， nodata ' + url + "  : " + JSON.stringify(message)
      // console.log(error || emptyMsg)
      // ipcMain.reply('send-mqtt-client-message-reply', error || emptyMsg)
    })
    return true
  },
  getClientType (ipcMain, client, message) {
    // 发布消息
    if (!client || !client.connected) {
      console.log('客户端未连接')
      ipcMain.reply('get-mqtt-client-message-reply', '客户端未连接')
      return false
    }
    //发送数据需要转换成json字符串
    message = JSON.stringify(message)

    client.publish('api/GetClientType', message, {
      qos: 2
    }, (error) => {
      console.log(error || '消息发布成功')
      ipcMain.reply('get-client-type-reply', error || '消息发布成功')
    })
    return true
  },
  closeConnect (ipcMain, client) {
    if (client && client.connected) {
      // 尝试着不关MQTT
      client.end()
      // ipcMain.reply('close-mqtt-connect-reply', 'mqtt已关闭')
    } else {
      console.log('客户端未连接')
      ipcMain.reply('close-mqtt-connect-reply', 'mqtt未连接')
      return false
    }
  }
}